package com.mhz.cae.objects;

import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.extension.physics.box2d.PhysicsConnector;
import org.anddev.andengine.extension.physics.box2d.PhysicsFactory;
import org.anddev.andengine.extension.physics.box2d.PhysicsWorld;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TextureRegion;

import android.content.Context;

import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.mhz.cae.util.CoordonateConverter;

/**
 * Represents a ball object
 * @author milhouz
 */
public class TennisBall implements Item {

	// The original object coordonates
	private final float mOriginalX;
	private final float mOriginalY;

	// The object textures
	private static TextureRegion mCircleFaceTextureRegion;

	// Animated Sprite and body
	private Sprite mFace;
	private Body mBody;

	private TennisBall(final float pX, final float pY) {
		this.mOriginalX = pX;
		this.mOriginalY = pY;
	}

	public static TennisBall createObject(final float pX, final float pY) {
		return new TennisBall(pX, pY);
	}

	public static void loadResource(final Context context, final BitmapTextureAtlas bitmapTextureAtlas) {
		if (mCircleFaceTextureRegion == null) {
			mCircleFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset( //
					bitmapTextureAtlas //
					, context //
					, "tennis_ball.png" //
					, 0 //
					, 0);

		}
	}

	@Override
	public void initObject(final PhysicsWorld physicsWorld, final Scene scene) {
		final FixtureDef objectFixtureDef = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f);
		// Create Face
		mFace = new Sprite(mOriginalX, mOriginalY, mCircleFaceTextureRegion);
		// Attach Face to the scene
		scene.attachChild(mFace);
		// Create Body
		mBody = PhysicsFactory.createCircleBody(physicsWorld, mFace, BodyType.DynamicBody, objectFixtureDef);
		// Regiter connector
		physicsWorld.registerPhysicsConnector(new PhysicsConnector(mFace, mBody, true, true));
	}

	@Override
	public void resetObject() {
		mBody.setLinearVelocity(0, 0);
		mBody.setAngularVelocity(0);
		mBody.setTransform(CoordonateConverter.faceToBody(mOriginalX, mFace.getWidth()), CoordonateConverter.faceToBody(mOriginalY, mFace.getHeight()), 0);
	}

	@Override
	public void setSelected(boolean pSelected) {
		// TODO Auto-generated method stub
	}

	@Override
	public void transform(PhysicsWorld pPhysicWorld, float pZoomFactor, float pAngle) {
		// TODO Auto-generated method stub
	}
}
